const COS = require('cos-wx-sdk-v5');
var http = require('@/http/http.js');
var that = this;
const cos = new COS({
	getAuthorization: function(options, callback) {
		http.get('/orders/getCredentials', {}, (res) => {
			if (res.data.success) {
				callback({
					TmpSecretId: res.data.result.TmpSecretId,
					TmpSecretKey: res.data.result.TmpSecretKey,
					SecurityToken: res.data.result.SecurityToken,
					ExpiredTime: res.data.result.ExpiredTime,
				});
			} else {
				that.$refs.uToast.show({
					title: '获取临时密钥失败',
					type: 'error'
				})
			}
		})
	}
});
export default {
	cosUpload(filePath, fileName, callback, progress) {

		cos.uploadFile({
			Bucket: 'car2-1256191950', // 必须
			Region: 'ap-guangzhou', // 存储桶所在地域，必须字段
			StorageClass: 'STANDARD',
			Key: fileName, // 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段
			FilePath: filePath, // 上传文件对象，必须字段
			onProgress: function(progressData) {
				console.log(JSON.stringify(progressData));
			}
		}, function(err, data) {
			if (err) {
				console.log('上传失败', err);
			} else {
				console.log('上传成功', data);
			}
		});

	},
	generateFileName(originalName) {
		const extension = originalName.substring(originalName.lastIndexOf('.'));
		const timestamp = new Date().getTime();
		const random = Math.floor(Math.random() * 10000);
		return `${timestamp}_${random}${extension}`;
	},
	uploadFiles(files, dir, callback) {
		if (!dir) {
			uni.showToast({
				title: '保存路径不存在',
			})
			return;
		}
		if (files.length == 0) {
			callback({
				files: []
			});
			return;
		}
		uni.showLoading({
			title: '上传中'
		});
		var that = this;
		const fileList = files.filter(item => item.file != undefined).map(function(file) {
			var fileKey=that.generateFileName(file.file.path);
			const extension = fileKey.substring(fileKey.lastIndexOf('.')+1).toLowerCase();
			var fileName = dir + that.generateFileName(file.file.path);
			return Object.assign(file, {
				FilePath: file.file.path, // 必须
				FileSize: file.file.size, // v1.4.3之前的版本必须，v1.4.3及以后的版本非必须
				Bucket: 'car2-1256191950', // 必须
				Region: 'ap-guangzhou', // 存储桶所在地域，必须字段
				Key: fileName, // 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段
				ContentType: extension=='pdf'?'application/pdf':'image/jpeg',
				onTaskReady: function(taskId) {
					// taskId 可通过队列操作来取消上传 cos.cancelTask(taskId)、停止上传 cos.pauseTask(taskId)、重新开始上传 cos.restartTask(taskId)
					// console.log(taskId);
				},
			
			});
		});
		if (fileList.length == 0) {
			callback({
				files: []
			});
			return;
		} 
		cos.uploadFiles({
			files: fileList,
			SliceSize: 1024 * 1024 * 10, // 设置大于10MB采用分块上传，按需调整，最小支持1MB
			onProgress: function(info) {
				var percent = parseInt(info.percent * 10000) / 100;
				var speed = parseInt(info.speed / 1024 / 1024 * 100) / 100;
				console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
			},
			onFileFinish: function(err, data, options) {
				console.log(options.Key + '上传' + (err ? '失败' : '完成'));
			},
		}, function(err, data) {
			uni.hideLoading();
			// 上传失败的任务
			const failedList = data.files.filter(item => item.error);
			console.log(failedList.length > 0 ? `部分失败:${failedList}` : '全部成功');
			if (data) {
				callback(data);
			}
		});
	}


}